<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="所属项目" prop="projectId">
        <el-select
            class="search-width"
            filterable clearable v-model="queryParams.projectId" placeholder="请选择所属项目">
          <el-option
              v-for="item in allProjectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="甲方名称" prop="principalName">
        <el-input maxlength="50"
                  class="search-width"
                  v-model="queryParams.principalName"
                  placeholder="请输入委托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="受托方名称" prop="trusteeName">
        <el-input maxlength="50"
                  class="search-width"
                  v-model="queryParams.trusteeName"
                  placeholder="请输入受托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="classifyCode">
        <el-select filterable clearable
                   class="search-width"
                   v-model="queryParams.classifyCode" placeholder="请选择项目类型">
          <el-option
              v-for="dict in project_classify"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开票状态" prop="status">
        <el-select
            class="search-width"
            clearable v-model="queryParams.status" placeholder="开票状态">
          <el-option key="0" label="待开票" value="0"/>
          <el-option key="1" label="已开票" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="开票日期" prop="invoiceTime">
        <el-date-picker class="search-width"
                        v-model="queryParams.invoiceTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        @change="handleTime">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['biz:bizInvoice:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['biz:bizInvoice:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:bizInvoice:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['biz:bizInvoice:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizInvoiceList" border>
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.invoiceList"
                    row-class-name="success-row"
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="left"/>
            <el-table-column label="序号" type="index" align="left" width="60"/>
            <el-table-column label="开票日期" align="left" prop="invoiceTime" width="120"/>
            <el-table-column label="发票类型" align="left" prop="invoiceType" width="120" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="invoice_type" :value="scope.row.invoiceType"/>
              </template>
            </el-table-column>
            <el-table-column label="开票主体" align="left" prop="invoiceSubject" show-overflow-tooltip/>
            <el-table-column label="发票抬头" align="left" prop="headerTitle" show-overflow-tooltip/>
            <el-table-column label="发票金额" align="left" prop="invoiceMoney" width="120">
              <template #default="scope">
                <span>{{ formatMoney(scope.row.invoiceMoney) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发票号码" align="left" prop="invoiceNo" show-overflow-tooltip/>
            <el-table-column label="应税服务名称" align="left" prop="invoiceService" min-width="120"
                             show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="invoice_service" :value="scope.row.invoiceService"/>
              </template>
            </el-table-column>
            <el-table-column label="开票人" align="left" prop="invoiceUserName" width="120"/>
            <el-table-column label="创建时间" align="left" prop="createTime" width="180"/>
            <el-table-column label="操作" align="left" width="90px" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                             v-hasPermi="['biz:bizInvoice:edit']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                             v-hasPermi="['biz:bizInvoice:remove']">
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" align="left" width="60"/>
      <el-table-column label="项目名称" align="left" prop="projectName" min-width="200" show-overflow-tooltip/>
      <el-table-column label="项目板块" align="left" prop="sectorName" width="160" show-overflow-tooltip/>
      <el-table-column label="合同金额" align="left" prop="totalAmount" width="180">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.totalAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已开票金额" align="left" prop="invoiceAmount" width="180">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.invoiceAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未开票金额" align="left" prop="unInvoiceAmount" width="180">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.unInvoiceAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划开票次数" align="left" prop="invoicePlan" width="180">
        <template #default="scope">
          <el-popover placement="bottom" :width="330" trigger="hover">
            <template #reference>
              <el-text style="color: blue;cursor: pointer;">{{ scope.row.invoicePlan }}</el-text>
            </template>
            <el-table :data="scope.row.planList">
              <el-table-column prop="stage" label="款项名称" width="180"/>
              <el-table-column prop="time" label="时间" width="120"/>
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="实际开票次数" align="left" prop="invoiceReal" width="180"/>
      <el-table-column fixed="right" label="操作" align="left" width="110">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleNew(scope.row)"
                     v-hasPermi="['biz:bizInvoice:edit']">开票登记
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目开票对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="800px" append-to-body
               @close="cancel">
      <el-form ref="bizInvoiceRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="剩余开票额" class="custom-red-label-color">
          <el-text style="color:red">{{ surplusAmount }}</el-text>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select :disabled="!selectProject" filterable clearable v-model="form.projectId" @change="changeProject"
                     placeholder="请选择所属项目">
            <el-option
                v-for="item in allProjectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票抬头" prop="headerId">
          <el-select filterable clearable v-model="form.headerId" placeholder="请选择发票抬头">
            <el-option
                v-for="item in allInvoiceHeaderList"
                :key="item.id"
                :label="item.headerTitle"
                :value="item.id"
                @click.native="changeHeader(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
            <el-option
                v-for="dict in invoice_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位名称" prop="companyName">
          <el-input maxlength="50" v-model="form.companyName" placeholder="请输入单位名称"/>
        </el-form-item>
        <el-form-item label="开户银行" prop="depositBank">
          <el-input maxlength="50" v-model="form.depositBank" placeholder="请输入开户银行"/>
        </el-form-item>
        <el-form-item label="开户行账号" prop="cardNumber">
          <el-input maxlength="50" v-model="form.cardNumber" placeholder="请输入开户行账号"/>
        </el-form-item>
        <el-form-item label="开票主体" prop="invoiceSubjectId">
          <el-select v-model="form.invoiceSubjectId" placeholder="请选择开票主体">
            <el-option
                v-for="item in trusteeList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票日期" prop="invoiceTime">
          <el-date-picker clearable
                          v-model="form.invoiceTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开票日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开票金额" prop="invoiceMoney">
          <CurrencyInput maxlength="50" v-model="form.invoiceMoney" placeholder="请输入开票金额"/>
        </el-form-item>
        <el-form-item label="发票号码" prop="invoiceNo">
          <el-input maxlength="50" v-model="form.invoiceNo" placeholder="请输入发票号码"/>
        </el-form-item>
        <el-form-item label="应税服务名称" prop="invoiceService">
          <el-select v-model="form.invoiceService" placeholder="请选择应税服务名称">
            <el-option
                v-for="dict in invoice_service"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input maxlength="500" v-model="form.memo" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BizInvoice">
import {
  listBizInvoice,
  getBizInvoice,
  delBizInvoice,
  addBizInvoice,
  updateBizInvoice,
  getSurplus
} from "@/api/biz/bizInvoice";
import {listAllProject} from "@/api/biz/bizProject";
import {listAllInvoiceHeader} from "@/api/biz/bizInvoiceHeader";
import CurrencyInput from '@/components/CurrencyInput.vue';
import {currentDate} from '@/utils/dateutil';
import {listAllTrustee} from "@/api/biz/bizTrustee";
import {formatMoney} from '@/utils/money';

const {proxy} = getCurrentInstance();
const {
  invoice_service,
  invoice_type,
  project_classify
} = proxy.useDict('invoice_service', 'invoice_type', 'project_classify');
const route = useRoute();
const router = useRouter();
const paramProjectId = ref('');
paramProjectId.value = route.query.invoiceProjectId;
// 计算属性用于获取查询参数 t
const queryParamT = computed(() => route.query.invoiceProjectId);
// 监听 queryParamT 的变化
watch(queryParamT, (newValue, oldValue) => {
  paramProjectId.value = newValue;
  invoiceListAllProject();
});

const trusteeList = ref([]);
const allProjectList = ref([]);
const allInvoiceHeaderList = ref([]);
const bizInvoiceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectProject = ref(true);
const surplusAmount = ref(0);
const add = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    principalName: null,
    trusteeName: null,
    classifyCode: null,
    status: null,
    invoiceTimeStart: null,
    invoiceTimeEnd: null,
  },
  rules: {
    projectId: [
      {required: true, message: "所属项目不能为空", trigger: "submit"}
    ],
    headerId: [
      {required: true, message: "发票抬头不能为空", trigger: "submit"}
    ],
    invoiceType: [
      {required: true, message: "发票类型不能为空", trigger: "submit"}
    ],
    companyName: [
      {required: true, message: "单位名称不能为空", trigger: "submit"}
    ],
    invoiceSubjectId: [
      {required: true, message: "开票主体不能为空", trigger: "submit"}
    ],
    invoiceTime: [
      {required: true, message: "开票日期不能为空", trigger: "submit"}
    ],
    invoiceMoney: [
      {required: true, message: "开票金额不能为空", trigger: "submit"}
    ],
    invoiceNo: [
      {required: true, message: "发票号码不能为空", trigger: "submit"}
    ],
    invoiceService: [
      {required: true, message: "应税服务名称不能为空", trigger: "submit"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询项目开票列表 */
function getList() {
  loading.value = true;
  listBizInvoice(queryParams.value).then(response => {
    bizInvoiceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  const {invoiceProjectId, ...query} = route.query;
  router.replace({path: route.path, query});
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    projectId: null,
    headerId: null,
    invoiceType: null,
    companyName: null,
    depositBank: null,
    cardNumber: null,
    invoiceSubjectId: null,
    invoiceTime: null,
    invoiceMoney: null,
    invoiceNo: null,
    invoiceUserId: null,
    invoiceService: null,
    memo: null
  };
  proxy.resetForm("bizInvoiceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleTime(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  selectProject.value = true;
  open.value = true;
  title.value = "添加项目开票";
  add.value = 0;
}

function handleNew(row) {
  reset();
  selectProject.value = false;
  open.value = true;
  title.value = "添加项目开票";
  form.value.projectId = row.projectId;
  form.value.invoiceSubjectId = row.trusteeId;
  let t = allInvoiceHeaderList.value.find(r => r.phone == row.principalPhone);
  if (t) {
    form.value.headerId = t.id;
    form.value.invoiceType = t.invoiceType
    form.value.companyName = t.companyName
    form.value.depositBank = t.depositBank
    form.value.cardNumber = t.cardNumber
  }
  add.value = 0;
  changeProject();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBizInvoice(_id).then(response => {
    form.value = response.data;
    add.value = form.value.invoiceMoney;
    selectProject.value = true;
    open.value = true;
    title.value = "修改项目开票";
    changeProject();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizInvoiceRef"].validate(valid => {
    if (valid) {
      if (form.value.invoiceMoney > surplusAmount.value) {
        proxy.$modal.msgError("开票金额不能大于剩余开票额");
        return;
      }
      if (form.value.id != null) {
        updateBizInvoice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBizInvoice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除项目开票数据项？').then(function () {
    return delBizInvoice(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/bizInvoice/export', {
    ...queryParams.value
  }, `开票-${currentDate()}.xlsx`)
}

function invoiceListAllProject() {
  listAllProject({}).then(response => {
    allProjectList.value = response.data;
    if (paramProjectId.value) {
      //参数存在，打开弹窗
      reset();
      open.value = true;
      title.value = "添加项目开票";
      form.value.projectId = Number(paramProjectId.value);
    }
  });
}

function getListAllInvoiceHeader() {
  listAllInvoiceHeader({}).then(response => {
    allInvoiceHeaderList.value = response.data;
  });
}

function changeHeader(row) {
  form.value.invoiceType = row.invoiceType
  form.value.companyName = row.companyName
  form.value.depositBank = row.depositBank
  form.value.cardNumber = row.cardNumber
}

function handleTime(value) {
  queryParams.value.invoiceTimeStart=null;
  queryParams.value.invoiceTimeEnd=null;
  if (value && value.length > 0) {
    queryParams.value.invoiceTimeStart = value[0] + " 00:00:00";
  }
  if (value && value.length > 1) {
    queryParams.value.invoiceTimeEnd = value[1] + " 23:59:59";
  }
}

function changeProject() {
  getSurplus(form.value.projectId).then(response => {
    surplusAmount.value = response.data + add.value;
  });
}

function getListAllTrustee() {
  listAllTrustee().then(response => {
    trusteeList.value = response.data;
  });
}

getList();
invoiceListAllProject();
getListAllInvoiceHeader();
getListAllTrustee();
</script>
<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.custom-red-label-color .el-form-item__label {
  color: red; /* 这里设置为红色 */
}
</style>
